package com.example.demo.udp;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.example.demo.websocket.WebSocket;
import io.netty.buffer.ByteBuf;
import io.netty.channel.socket.DatagramPacket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * Created on 2020/8/5.
 */
@Service
public class UDPService {
    private Integer udpServerPort = 10004;
    private int last = 0;//上一次数据结果

//    @PostConstruct
    public void initUDPServer() {
        UDPServer.init(udpServerPort);
    }

    //处理接收到的数据
    public void handleReceivedPackage(DatagramPacket datagramPacket) {
        ByteBuf buf = datagramPacket.content();
        if(buf.isReadable() && buf.readableBytes()>0) {
            byte[] req = new byte[buf.readableBytes()];
            buf.readBytes(req);
            String body = null;
            try {
                body = new String(req, "UTF-8");
                System.out.println(new Date() + "---接收到的数据---" +body);
                JSONObject resultObj = parseJSONData(body);
                if(resultObj!=null) {
                    WebSocket.sendMessage(resultObj, "1234");
                }
                System.out.println(new Date() + "---发送给前端的下压数据---" + resultObj);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    private Integer parseData(String data) {
        int result = 0;//数据处理结果
        if(data.length()>0 && data.startsWith("0A")) {
            String[] dataArray = data.split(" ");
            System.out.println(dataArray[7]);
            if("AA".equals(dataArray[7])) {//下压
                result = Integer.parseInt(dataArray[8], 16);
            }else if("BB".equals(dataArray[7])) {//反弹
                result = last - Integer.parseInt(dataArray[8], 16);
            }
            last = result;
        }
        System.out.println(result);
        return result;
    }


    private JSONObject parseJSONData(String data) {
        JSONObject jsonObject = new JSONObject();

        int result = 0;//数据处理结果
        if(data.length()>0 && data.startsWith("0A")) {
            jsonObject.set("receiveData", data);
            String[] dataArray = data.split(" ");
            System.out.println(dataArray[7]);
            if("AA".equals(dataArray[7])) {//下压
                result = Integer.parseInt(dataArray[8], 16);
            }else if("BB".equals(dataArray[7])) {//反弹
                result = last - Integer.parseInt(dataArray[8], 16);
            }
            last = result;

            jsonObject.set("resultData", result);
        }

        return jsonObject;
    }
}
